import React from 'react';
import dayjs from 'dayjs';
import { Link, Popover, Tooltip, Typography } from '@arco-design/web-react';
import store from '@/store';
import clipboard from '@/utils/clipboard';
import Status from '@/components/Status';

function dynamicFormat(input) {
  if (!input) {
    return '';
  }
  const inputArr = input
    .replace(/-/g, '')
    .replace(/[^0-9 ]+/, '')
    .split('');
  const split = [
    [0, 3],
    [3, 7],
    [7, 14],
    [14, 15],
  ];
  const result = [];
  for (let i = 0; i < split.length; i++) {
    const text = inputArr.slice(split[i][0], split[i][1]).join('');
    if (text) {
      result.push(inputArr.slice(split[i][0], split[i][1]).join(''));
    }
  }
  return result.join('-');
}

export function getColumns(
  t: unknown,
  callback: (record: Record<string, unknown>, type: string) => Promise<void>,
  tableColumns: Array<unknown>,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  options: Array<any>,
  lang: string
) {
  const defaultColumns = options.filter((a) => tableColumns.includes(a.value));

  const onCell = (a: Record<string, unknown>) => {
    callback(a, 'details');
    // return {
    //   onClick: () => callback(a, 'details'),
    // };
  };

  const customColumns = [
    {
      title: t['searchTable.columns.number'],
      dataIndex: 'refNumber',
      width: 290,
      render: (a, b) => {
        return (
          <Link hoverable={false}>
            <Status status={b.status?.key}></Status>
            <Typography.Text
              underline
              onClick={() => {
                onCell({ refNumber: a });
              }}
            >
              {a}
            </Typography.Text>
            <Typography.Text
              underline
              copyable
              onClick={() => {
                clipboard(a);

                store.dispatch({
                  type: 'update-referenceDetails',
                  payload: {
                    referenceDetails: { refNumber: a, fullName: b.fullName },
                  },
                });
              }}
            ></Typography.Text>
          </Link>
        );
      },
      sorter: true,
    },
    {
      title: t['searchTable.columns.created'],
      dataIndex: 'createdAt',
      width: 200,
      render: (x: string | number | Date | dayjs.Dayjs) => (
        <div className="ltr-ipt">{x ? x : '--'}</div>
      ),
    },
    {
      title: t['searchTable.columns.links'],
      dataIndex: 'links',
      width: 240,
      render: (a: string[]) => {
        const node =
          a &&
          a.map((b, index) => (
            <Link key={index}>
              <Typography.Text
                underline
                onClick={() => {
                  onCell({ refNumber: b });
                }}
              >
                {b}
              </Typography.Text>
            </Link>
          ));
        return <div className={'ltr'}>{node || '--'}</div>;
      },
    },
    {
      title: t['searchTable.columns.emirates'],
      dataIndex: 'emirate',
      width: 200,
      render: (a: { value: { [x: string]: any } }): JSX.Element => {
        return <>{a?.value[lang === 'en-US' ? 'en' : 'ar']}</>;
      },
    },
    {
      title: t['searchTable.columns.eid'],
      dataIndex: 'eid',
      width: 190,
      render: (a): JSX.Element => {
        return <>{dynamicFormat(a) || '--'}</>;
      },
    },
    {
      title: t['searchTable.columns.entityName'],
      dataIndex: 'emirateEntity',
      width: 200,
      render: (
        a: { [x: string]: any },
        b: { emirateEntityOther: any }
      ): JSX.Element => {
        const text = a ? a && a['name'] : b.emirateEntityOther || '--';
        return (
          <Tooltip content={text}>
            <div className="ellipsis">{text || '--'}</div>
          </Tooltip>
        );
      },
      sorter: true,
    },
    {
      title: t['searchTable.columns.entityNameAr'],
      dataIndex: 'emirateEntityAr',
      width: 200,
      render: (_, b: any): JSX.Element => {
        return <>{(b.emirateEntity && b.emirateEntity['nameAr']) || '--'}</>;
      },
      sorter: true,
    },
    {
      title: t['searchTable.columns.source'],
      dataIndex: 'source',
      width: 120,
      render: (a: { [x: string]: any }): JSX.Element => {
        return (
          <>
            {a ? a && a.value[lang === 'en-US' ? 'en' : 'ar'] : a.sourceOther}
          </>
        );
      },
    },
    {
      title: t['searchTable.columns.status'],
      dataIndex: 'status',
      width: 130,
      render: (a: { value: { [x: string]: any } }): JSX.Element => {
        return <>{a?.value[lang === 'en-US' ? 'en' : 'ar'] || '--'}</>;
      },
    },
    {
      title: t['searchTable.columns.taken'],
      dataIndex: 'actionTaken',
      width: 140,
      render: (a: { value: { [x: string]: any } }): JSX.Element => {
        return (
          <>
            <Tooltip content={a?.value[lang === 'en-US' ? 'en' : 'ar']}>
              <div className="ellipsis">
                {a?.value[lang === 'en-US' ? 'en' : 'ar'] || '--'}
              </div>
            </Tooltip>
          </>
        );
      },
    },
    {
      title: t['searchTable.columns.boxType'],
      dataIndex: 'violationBoxType',
      width: 220,
      render: (a: any): JSX.Element => {
        const text =
          Array.isArray(a) &&
          a.map((b) => b?.value[lang === 'en-US' ? 'en' : 'ar']).join(',');
        return (
          <Tooltip content={text}>
            <div className="ellipsis">{text || '--'}</div>
          </Tooltip>
        );
      },
    },
    {
      title: t['searchTable.columns.type'],
      dataIndex: 'violationType',
      width: 180,
      render: (_: any, b: any): JSX.Element => {
        let text = '';
        if (b.violationType) {
          text = b.violationType?.value[lang === 'en-US' ? 'en' : 'ar'];
        }
        if (b.violationTypeA) {
          text = b.violationTypeA
            .map((a) => a?.value[lang === 'en-US' ? 'en' : 'ar'])
            .join(', ');
        }
        if (b.violationTypeB) {
          text = b.violationTypeB
            .map((a) => a?.value[lang === 'en-US' ? 'en' : 'ar'])
            .join(', ');
        }
        return (
          <Tooltip content={text}>
            <div className="ellipsis">{text || '--'}</div>
          </Tooltip>
        );
      },
    },
    {
      title: t['searchTable.columns.person'],
      dataIndex: 'assignedPerson',
      width: 200,
      render: (a): JSX.Element => {
        return <>{(a && a.map((e) => e?.name).join(',')) || '--'}</>;
      },
    },
    {
      title: t['searchTable.columns.name'],
      dataIndex: 'fullName',
      width: 180,
      render: (a): JSX.Element => {
        return (
          <>
            <Tooltip content={a}>
              <div className="ellipsis">{a || '--'}</div>
            </Tooltip>
          </>
        );
      },
    },
    {
      title: t['searchTable.columns.desc'],
      dataIndex: 'violationDesc',
      width: 200,
      render: (a: any): JSX.Element => {
        return (
          <Tooltip
            content={
              a && (
                <div style={{ maxHeight: '50vh', overflow: 'auto' }}>{a}</div>
              )
            }
          >
            <div className="ellipsis">{a || '--'}</div>
          </Tooltip>
        );
      },
    },

    {
      title: t['searchTable.columns.AdditionalDetails'],
      dataIndex: 'violationAdditionalDetails',
      width: 200,
      render: (a: any): JSX.Element => {
        return (
          <Tooltip
            content={
              a && (
                <div style={{ maxHeight: '50vh', overflow: 'auto' }}>{a}</div>
              )
            }
          >
            <div className="ellipsis">{a || '--'}</div>
          </Tooltip>
        );
      },
    },
  ];

  const columns = defaultColumns.map((a) => {
    const k = customColumns.findIndex((b) => b.dataIndex === a.value);
    return k === -1
      ? {
          ...{
            title: a.label,
            dataIndex: a.value,
            // onCell: onCell,
          },
          ...(a.width ? { width: a.width } : {}),
        }
      : customColumns[k];
  });

  return columns;
}
